package com.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

@RestController
@RequestMapping("dynamic")
public class DynamicController {
    @Autowired
    RequestMappingHandlerMapping requestMappingHandlerMapping;

    public String hello(){
        return "hello world";
    }

    @PostMapping("create")
    @ResponseBody
    public String addRequestMapper() throws IllegalAccessException, InstantiationException {

        Class<?> entry = this.getClass();

        // hello 是方法名，ReflectionUtils 是 org.springframework.util 包
        Method methodName = ReflectionUtils.findMethod(entry, "hello");

        PatternsRequestCondition patterns = new PatternsRequestCondition("op/api/test/hello");

        RequestMethodsRequestCondition method = new RequestMethodsRequestCondition(RequestMethod.POST);
        RequestMappingInfo mappingInfo = new RequestMappingInfo(patterns, method, null, null, null, null, null);

        requestMappingHandlerMapping.registerMapping(mappingInfo, entry.newInstance(), methodName);
        return "success";
    }

}
